<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '优惠券' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  goods_all:[],
  data_ini:{
    type: [],
    category_id:[],
    cdp_type:[]
  },
  type_name:['泊时礼券','联名礼券'],
  type_select:[{
    'label':'泊时礼券',
    'value':0,
  },{
    'label':'联名礼券',
    'value':1,
  }]
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '优惠券',
  initForm: {},
  doCreate: api.createCoupon,
  doUpdate: api.updateCoupon,
  doDelete: api.deleteCoupon,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
  api.getProjectIni().then((res) => (data.data_ini = res.data))
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '类型',
    key: 'type',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => data.type_name[row.type] })
    },
  },
    {
    title: '优惠券名称',
    key: 'image',
    width: 80,
    align: 'left',

    render(row) {

      return h(NFlex, {},
        [h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.title)
        })]
      )

    },
  },
  {
    title: '面值',
    key: 'price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '来源卡项',
    key: 'card_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '效期(天)',
    key: 'longs',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '生成数量',
    key: 'nums',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '获得方式',
    key: 'get_type_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.get_type_name })
    },
  },
  {
    title: '发放状态',
    key: 'states',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.states,
        checkedValue: 0,
        uncheckedValue: 1,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.states = row.states === 1 ? 0 : 1
  try {
    await api.updateCoupon(row)
    $message?.success(row.states ? '已下架' : '已上架')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.states = row.states === 1 ? 0 : 1
  }
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}


function on_add(){
  handleAdd()
  // modalForm.value.is_sell = 1
  // modalForm.value.status = 1
  // modalForm.value.extra = 1
  get_drug_all()
}

function on_edit(row){
  handleEdit(row)
  get_drug_all()
}

function get_drug_all(){
  if(data.goods_all.length===0){
    api.getGoodsAll().then((res) => (data.goods_all = res.data))
  }
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton  type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建{{ nameFromInstance }}
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getCouponList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem :label="nameFromInstance+'名称'" :label-width="80">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 800px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <n-tabs type="line" animated size="large" pane-style="padding: 20px 0 0 0;">
               <n-tab-pane name="基础信息">

                <NFormItem label="来源商品" path="card_id">
                  <n-select
                    v-model:value="modalForm.card_id"
                    :options="data.goods_all"
                    placeholder="请选择来源商品"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="类型" path="type">
                  <n-select
                    v-model:value="modalForm.type"
                    :options="data.type_select"
                    placeholder="请选择类型"
                  />
                </NFormItem>
                <NFormItem label="名称" path="title">
                  <NInput v-model:value="modalForm.title" clearable placeholder="请输入名称" />
                </NFormItem>
                <NFormItem label="面值" path="price">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.price" placeholder="请输入价格" />
                </NFormItem>
                 <NFormItem label="生成数量" path="nums">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.nums" placeholder="请输入生成数量" />
                </NFormItem>
                 <NFormItem label="效期(天)" path="longs">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.longs" placeholder="请输入效期(天)" />
                </NFormItem>

                <NFormItem label="上架状态" path="states">
                  <NSwitch
                    v-model:value="modalForm.states"
                    :checked-value="0"
                    :unchecked-value="1"
                  />
                </NFormItem>
                 <NFormItem label="描述" path="remark">
                  <NInput type="textarea" v-model:value="modalForm.remark" clearable placeholder="请输入描述" />
                </NFormItem>

              </n-tab-pane>
              <n-tab-pane name="发放规则">
                <NFormItem label="可用分类" path="use_type">
                  <n-select
                    v-model:value="modalForm.use_type"
                    :options="data.data_ini.type"
                    placeholder="请选择可以使用的商品分类,不选为所有"
                    label-field="name"
                    value-field="id"
                    multiple
                  />
                </NFormItem>
                <NFormItem label="可以商品" path="use_card_ids">
                  <n-select
                    v-model:value="modalForm.use_card_ids"
                    :options="data.goods_all"
                    placeholder="请选择可以使用的商品,不选为所有"
                    label-field="name"
                    value-field="id"
                    multiple
                  />
                </NFormItem>
                <NFormItem label="使用起点" path="use_money">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.use_money" placeholder="请输入使用起点" />
                </NFormItem>

               </n-tab-pane>
            </n-tabs>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
